package com.heo.protocol.packet;

import org.apache.log4j.Logger;

import com.heo.util.ByteHelper;

public class ReadDeviceCodeReq extends BasePacket
{
  private int BODY_LENGTH = -1;// 包体长不确定
  private static final String PACKET_NAME = "[反向扫码请求包]";

  private static Logger log = Logger.getLogger(ReadDeviceCodeReq.class);

  private int channelIndex = 0;
  private String codeContent = null;

  /**
   * 通过网络传过来的流构建对象
   * 
   * @param totalLength
   * @param commandId
   * @param sequenceId
   * @param body
   * @throws Exception
   */
  public ReadDeviceCodeReq(String logHeader, SocketPacket packet) throws Exception
  {
    super.copyPacket(logHeader, PACKET_NAME, packet);
    makeBody();
  }

  public ReadDeviceCodeReq() throws Exception
  {
    super();
    super.commandId = DeviceCommand.READ_DEVICE_CODE_REQ;
    super.sequenceId = 0x01;
    if (codeContent == null)
    {
      super.totalLength = HEAD_LENGTH + 2;
    }
    else
    {
      super.totalLength = HEAD_LENGTH + 2 + codeContent.length();
    }
  }

  @Override
  public int getTotalLength()
  {
    if (codeContent == null)
    {
      return super.HEAD_LENGTH + 2;
    }
    else
    {
      return super.HEAD_LENGTH + 2 + codeContent.length();
    }
  }

  @Override
  public byte[] getPacketBody()
  {
    if (codeContent == null)
    {
      return ByteHelper.margeByte(ByteHelper.shortToByteArray((short) channelIndex), null, null, null, null, null, null, null, null, null);
    }
    else
    {
      return ByteHelper.margeByte(ByteHelper.shortToByteArray((short) channelIndex), codeContent.getBytes(), null, null, null, null, null, null, null, null);
    }
  }

  @Override
  public void makeBody() throws Exception
  {
    channelIndex = ByteHelper.byteToInt(packetBody, 0, 2);
    codeContent = ByteHelper.byteToString(packetBody, 2, packetBody.length - 2, (byte) 0);
    log.debug(super.logHeader + super.packetName + "数据包解析成功。");
  }

  public static void main(String[] args)
  {

  }

  public int getChannelIndex()
  {
    return channelIndex;
  }

  public void setChannelIndex(int channelIndex)
  {
    this.channelIndex = channelIndex;
  }

  public String getCodeContent()
  {
    return codeContent;
  }

  public void setCodeContent(String codeContent)
  {
    this.codeContent = codeContent;
  }

}
